import dayjs from "dayjs";
import conditionsDiscard from "../form/conditionsDiscard.vue";
import conditionsOutbound from "../form/conditionsOutbound.vue";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { tags_list } from "@/api/tag"
import { customer_list, customer_abandoned, customer_abandoned_batch } from "@/api/customer"
import { addDialog } from "@/components/ReDialog";
import { type Ref, reactive, ref, onMounted, h, toRaw, computed } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps,conditionsAllocateItemProps } from "./types";
import { deviceDetection } from "@pureadmin/utils";
import { useUserStoreHook } from "@/store/modules/user";
import { customerData_toTask } from "@/api/outbound";
export function useRole(detailRef: Ref) {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_cd_gh_tofq_condition: false, // 按条件删除到废弃
    is_cd_gh_table: false, // 公海客池列表
    is_cd_gh_tocall: false, // 按条件添加到外呼
    is_cd_gh_tofq_batch: false, // 批量删除到废弃
  })

  const shortcuts = [
    {
      text: "上周",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        return [start, end];
      }
    },
    {
      text: "上个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        return [start, end];
      }
    },
    {
      text: "三个月前",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        return [start, end];
      }
    }
  ];
  const labelList = ref([])
  const sourceList = ref([{
    value: "exchange",
    label: "兑领"
  }, {
    value: "third",
    label: "第三方自导入"
  }])
  const form = reactive({
    type: "gonghai",
    keyword: "",
    tag_id: "",
    source_by: "",
    entry_at: "",
    insea_times: "",
    page: 1,
    size: 10
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns = reactive<TableColumnList>([
    {
      type: "selection",
      align: "left"
    },
    {
      label: "企业名称",
      prop: "company_name",
      minWidth: 200
    },
    {
      label: "客户名称",
      prop: "name",
      minWidth: 100
    },
    {
      label: "联系电话",
      prop: "phone",
      minWidth: 140
    },
    {
      label: "地区",
      prop: "address_path",
      minWidth: 180,
    },
    {
      label: "客户标签",
      prop: "tag_ids",
      minWidth: 140,
      formatter: ({ tag_ids }) => {
        if (!tag_ids) return ''
        let tagIds = tag_ids.split(',').map(item => item.replaceAll('_', ''))
        return tagIds.map(item => labelList.value.find(tag => tag.id === item)?.name).join(',')
      }
    },
    {
      label: "数据来源",
      prop: "source_by",
      minWidth: 160,
      formatter: ({ source_by }) => {
        if (!source_by) return ''
        return sourceList.value.filter(item => item.value == source_by)[0].label
      }
    },
    {
      label: "累计进入公海次数",
      prop: "insea_times",
      minWidth: 140
    },
    {
      label: "最新进入公海时间",
      prop: "insea_at",
      minWidth: 140,
      formatter: ({ insea_at }) =>  insea_at == 0 ? '' : dayjs.unix(insea_at).format("YYYY-MM-DD")
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ]);

  const tableRef = ref();
  const multipleSelection = ref([]);
  const detailInfo = ref()

  function lookCustomer(row) {
    detailInfo.value = row;
    detailRef.value.openDrawer(row.id);
  }

  function handleSizeChange(val: number) {
    form.size = val;
    pagination.pageSize = val
    onSearch(); // 刷新表格数据
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    pagination.currentPage = val
    onSearch(); // 刷新表格数据
  }

  function handleSelectionChange(val) {
    multipleSelection.value = val;
  }

  function handleSelectionClear() {
    const { toggleRowSelection, clearSelection } = tableRef.value.getTableRef();
    clearSelection();
  }

  // 按条件删除到废弃客池
  const formRef = ref();
  function conditionsDiscardClick() {
    addDialog({
      title: '按条件删除到废弃客池',
      props: {
        formInline: {
          labelOptions: labelList.value,
          tag_ids: "",
          sourceOptions: sourceList.value,
          source: "",
          created_at: "",
          insea_times: null,
          type: 1,
          num: null
        }
      },
      width: "680px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(conditionsDiscard, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`操作成功！`, {
            type: "success"
          });
          setTimeout(() => {
            done(); // 关闭弹框
            onSearch(); // 刷新表格数据
          }, 1000);
        }
        // 客户参数选项，至少需要填写一个
        if (curData.tag_ids || curData.source || curData.created_at.length || curData.insea_times) {
          ElMessageBox.confirm("确定执行该操作？", "重要提示", {
            type: "warning"
          }).then(() => {
            let curForm: any = {}
            if (curData.tag_ids) curForm.tag_ids = curData.tag_ids
            if (curData.source) curForm.source = curData.source
            if (curData.created_at.length) {
              let startTime = dayjs(curData.created_at[0]).format("YYYY-MM-DD")
              let endTime = dayjs(curData.created_at[1]).format("YYYY-MM-DD")
              curForm.created_at = `${startTime},${endTime}`
            }
            if (curData.insea_times) curForm.insea_times = curData.insea_times
            if (curData.type == 2 || curData.num) curForm.num = curData.num
            customer_abandoned(curForm).then(res => {
              if (res.code == 1000) {
                chores();
              } else {
                message(res.msg, { type: "error" });
              }
            });
          }).catch(() => {});
        } else {
          ElMessageBox.confirm("客户参数选项，至少需要填写一个", "重要提示", {
            type: "error"
          }).then(() => {}).catch(() => {});
        }
      }
    });
  }

  // 删除到废弃客池
  function discardClick(row) {
    ElMessageBox.confirm("确定执行该操作？", "重要提示", {
      type: "warning"
    })
      .then(() => {
        if (row && row == 'detail') {
          customer_abandoned_batch({
            ids_json: `${detailInfo.value.id}:${detailInfo.value.table_at}:${detailInfo.value.version}`
          }).then(res => {
            if (res.code == 1000) {
              message(`操作成功！`, {
                type: "success"
              });
              setTimeout(() => {
                detailRef.value.closeDrawer();
                onSearch(); // 刷新表格数据
              }, 1000);
            } else {
              message(res.msg, { type: "error" });
            }
          });
        } else {
          let curForm: any = {}
          curForm.ids_json = multipleSelection.value.map(item => `${item.id}:${item.table_at}:${item.version}`).join(",")
          customer_abandoned_batch(curForm).then(res => {
            if (res.code == 1000) {
              message(`操作成功！`, {
                type: "success"
              });
              setTimeout(() => {
                multipleSelection.value = [];
                onSearch(); // 刷新表格数据
              }, 1000);
            } else {
              message(res.msg, { type: "error" });
            }
          });
        }

      })
      .catch(() => {});
  }

  // 按条件添加到外呼任务
    const conditionsOutboundFormRef = ref();
    function conditionsOutboundClick(callback?: (...args: any[]) => any) {
      addDialog({
        title: "按条件添加到外呼任务",
        props: {
          formInline: {
            labelOptions: labelList.value,
            tag_id: "",
            sourceOptions: sourceList.value,
            source: "",
            intention: [],
            called_times: "",
            entry_at: "",
            numberBy: "all",
            size: "",
            sortMode: 1,
            outboundProject: "",
            intend_status: "",
            page: "",
            sourceId: null,
            Process: null,
            showProgress: false
          }
        },
        width: "680px",
        draggable: true,
        fullscreen: deviceDetection(),
        fullscreenIcon: true,
        closeOnClickModal: false,
        contentRenderer: () =>
          h(conditionsOutbound, {
            ref: conditionsOutboundFormRef,
            formInline: null
          }),
        beforeSure: (done, { options }) => {
          const FormRef = conditionsOutboundFormRef.value.getRef();
          const curData = options.props.formInline as conditionsAllocateItemProps;
          function chores() {
            message(`操作成功！`, {
              type: "success"
            });
            done(); // 关闭弹框
            onSearch(); // 刷新表格数据
          }
          FormRef.validate(valid => {
            if (valid) {
              // 客户参数选项，至少需要填写一个
              if (
                curData.tag_id ||
                curData.source ||
                curData.intention.length ||
                curData.called_times ||
                curData.entry_at||
                curData.intend_status
              ) {
                ElMessageBox.confirm("确定执行该操作？", "重要提示", {
                  type: "warning"
                })
                  .then(() => {
                    customerData_toTask({
                      numberBy: curData.numberBy,
                      page: curData.page,
                      size: curData.size,
                      tag_id: curData.tag_id,
                      source: curData.source,
                      called_times: curData.called_times,
                      entry_at: curData.entry_at,
                      intend_status: curData.intend_status,
                      sourceId: curData.sourceId,
                      from:"gonghai"
                    }).then(res => {
                      if (res.code == 1000) {
                        localStorage.setItem('progressID', res.data.logId)
                        callback?.(res.data.logId);

                        chores();
                      }
                    });
                  })
                  .catch(() => {});
              } else {
                ElMessageBox.confirm(
                  "客户参数选项，至少需要填写一个",
                  "重要提示",
                  {
                    type: "error"
                  }
                )
                  .then(() => {})
                  .catch(() => {});
              }
            }
          });
        }
      });
    }

  function handleOffline(row) {
    message(`${row.username}已被强制下线`, { type: "success" });
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    let queryFrom = { ...form };

    if (queryFrom.entry_at.length) {
      let startTime = dayjs(queryFrom.entry_at[0]).format("YYYY-MM-DD")
      let endTime = dayjs(queryFrom.entry_at[1]).format("YYYY-MM-DD")
      queryFrom.entry_at = `${startTime},${endTime}`
    }

    const result = await customer_list(toRaw(queryFrom));

    dataList.value = result.data.list;
    pagination.total = result.data.total;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    getLabelList()

    /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/customerManagement/data/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(([key, value]) => value.onpage === "/customerManagement/data/index");
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);
      // cd_gh
      console.log(homeDataObj)
      if (homeDataObj.cd_gh && homeDataObj.cd_gh.childs) {
        let permiss = homeDataObj.cd_gh.childs.join(',')
        permissions.is_cd_gh_tofq_condition = permiss.includes('cd_gh_tofq_condition') ? true : false
        permissions.is_cd_gh_table = permiss.includes('cd_gh_table') ? true : false
        permissions.is_cd_gh_tocall = permiss.includes('cd_gh_tocall') ? true : false
        if (permiss.includes('cd_gh_table')) onSearch();
      }
      // cd_gh_table
      if (homeDataObj.cd_gh_table) {
        // batch
        if (homeDataObj.cd_gh_table.batch && homeDataObj.cd_gh_table.batch.length) {
          let permiss = homeDataObj.cd_gh_table.batch.join(',')
          permissions.is_cd_gh_tofq_batch = permiss.includes('cd_gh_tofq_batch') ? true : false
        }

        let tableRemove = homeDataObj.cd_gh_table.remove ? homeDataObj.cd_gh_table.remove.split(',') : []
        for (let i = 0; i < tableRemove.length; i++) {
          for (let a = 0; a < columns.length; a++) {
            if (columns[a].prop == tableRemove[i]) {
              columns.splice(a, 1)
            }
          }
        }
      }
    }
  });

  // 获取客户标签
  function getLabelList() {
    tags_list({
      page: 1,
      pagesize: 999,
      status: 1
    }).then(res => {
      labelList.value = res.data
    })
  }

  return {
    permissions,

    shortcuts,
    labelList,
    sourceList,
    form,
    loading,
    columns,
    dataList,
    pagination,
    tableRef,
    multipleSelection,

    conditionsDiscardClick,
    conditionsOutboundClick,
    discardClick,

    onSearch,
    resetForm,
    lookCustomer,
    handleOffline,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleSelectionClear
  };
}
